package net.xju3_4.service.impl;

import net.xju3_4.dao.PaymentDao;
import net.xju3_4.dao.RentalDao;
import net.xju3_4.entity.PaymentEntity;
import net.xju3_4.service.PaymentSimulationService;

import java.math.BigDecimal;
import java.util.*;

/**
 * 支付模拟服务实现类
 */
public class PaymentSimulationServiceImpl implements PaymentSimulationService {
    
    private PaymentDao paymentDao = new PaymentDao();
    private RentalDao rentalDao = new RentalDao();
    
    @Override
    public Map<String, Object> simulatePayment(Map<String, Object> paymentData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String orderId = (String) paymentData.get("orderId");
            String userId = (String) paymentData.get("userId");
            String paymentType = (String) paymentData.get("paymentType");
            String amountStr = (String) paymentData.get("amount");

            System.out.println("DEBUG: 开始支付处理 - orderId: " + orderId + ", userId: " + userId + ", paymentType: " + paymentType + ", amount: " + amountStr);

            // 生成支付流水号
            String paymentNo = generatePaymentNo();
            System.out.println("DEBUG: 生成支付流水号: " + paymentNo);

            // 创建支付记录
            PaymentEntity payment = new PaymentEntity();
            payment.setOrderId(Integer.parseInt(orderId));
            payment.setPaymentNo(paymentNo);
            payment.setPaymentType(Integer.parseInt(paymentType));
            payment.setAmount(new BigDecimal(amountStr));
            payment.setPaymentTime(new Date());
            payment.setStatus(1); // 1-已支付

            // 模拟支付处理（默认成功）
            boolean paymentSuccess = true;
            System.out.println("DEBUG: 支付处理结果: " + (paymentSuccess ? "成功" : "失败"));
            
            if (paymentSuccess) {
                // 保存支付记录
                boolean saveSuccess = paymentDao.insert(payment);
                System.out.println("DEBUG: 支付记录保存结果: " + saveSuccess);

                if (saveSuccess) {
                    // 更新订单状态为待取车（支付完成后）
                    System.out.println("DEBUG: 准备更新订单状态 - orderId: " + orderId + ", userId: " + userId + ", newStatus: 0");
                    boolean statusUpdateSuccess = rentalDao.updateRentalStatus(Integer.parseInt(orderId), 0, userId);
                    System.out.println("DEBUG: 订单状态更新结果: " + statusUpdateSuccess);

                    if (statusUpdateSuccess) {
                        result.put("success", true);
                        result.put("paymentNo", paymentNo);
                        result.put("message", "支付成功");
                        result.put("paymentTime", payment.getPaymentTime());
                        System.out.println("DEBUG: 支付流程完成，订单状态已更新为待取车");
                    } else {
                        result.put("success", false);
                        result.put("message", "支付成功但订单状态更新失败");
                        System.out.println("DEBUG: 支付成功但订单状态更新失败");
                    }
                } else {
                    result.put("success", false);
                    result.put("message", "支付记录保存失败");
                }
            } else {
                // 模拟支付失败
                payment.setStatus(0); // 0-未支付
                result.put("success", false);
                result.put("message", "支付失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "支付处理异常：" + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> getPaymentStatus(String orderId, String userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里应该查询支付记录，暂时模拟
            result.put("orderId", orderId);
            result.put("status", "paid");
            result.put("statusDesc", "已支付");
            result.put("paymentTime", new Date());
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> getPaymentMethods() {
        Map<String, Object> result = new HashMap<>();
        
        List<Map<String, Object>> methods = new ArrayList<>();
        
        // 微信支付
        Map<String, Object> wechat = new HashMap<>();
        wechat.put("type", "1");
        wechat.put("name", "微信支付");
        wechat.put("icon", "wechat");
        wechat.put("enabled", true);
        methods.add(wechat);
        
        // 支付宝
        Map<String, Object> alipay = new HashMap<>();
        alipay.put("type", "2");
        alipay.put("name", "支付宝");
        alipay.put("icon", "alipay");
        alipay.put("enabled", true);
        methods.add(alipay);
        
        result.put("methods", methods);
        return result;
    }
    
    @Override
    public Map<String, Object> createPaymentOrder(Map<String, Object> orderData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String rentalOrderId = (String) orderData.get("rentalOrderId");
            String userId = (String) orderData.get("userId");
            String amount = (String) orderData.get("amount");
            
            // 生成支付订单号
            String paymentOrderNo = "PAY" + System.currentTimeMillis();
            
            result.put("paymentOrderNo", paymentOrderNo);
            result.put("rentalOrderId", rentalOrderId);
            result.put("amount", amount);
            result.put("currency", "CNY");
            result.put("expireTime", new Date(System.currentTimeMillis() + 30 * 60 * 1000)); // 30分钟过期
            result.put("createTime", new Date());
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        
        return result;
    }
    
    @Override
    public boolean handlePaymentCallback(String paymentNo, String status) {
        try {
            // 模拟处理支付回调
            if ("success".equals(status)) {
                // 更新支付状态
                // 这里应该根据paymentNo查询并更新支付记录
                return true;
            } else {
                // 支付失败处理
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public String generatePaymentNo() {
        // 生成支付流水号：时间戳 + 随机数
        long timestamp = System.currentTimeMillis();
        int random = (int) (Math.random() * 10000);
        return "PAY" + timestamp + String.format("%04d", random);
    }
}
